<template>
  <div class="params_wrap">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{}"> 商品管理 </el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <!-- 
              警告区
              closable  是否可关闭，默认false
              show-icon  是否显示图标，默认true
           -->
        <el-alert
          title="注意：只允许为第三级分类设置相关参数！"
          type="warning"
          :closable="false"
          show-icon
        >
        </el-alert>
      </el-row>
      <!-- 选择商品分类区 -->
      <el-row style="margin: 15px 0">
        <span>选择商品分类：</span>
        <el-cascader
          v-model="selectedCateKeys"
          :options="goodsCateList"
          :props="cateProps"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <!-- 
        tab页签区
          v-model  绑定值，选中选项卡的 name
          @tab-click  tab被点击切换时触发该函数

       -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >
            添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="handleClosed(index, scope.row)"
                  closable
                >
                  {{ item }}
                </el-tag>
                <!-- 文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >
            添加属性
          </el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="handleClosed(index, scope.row)"
                  closable
                >
                  {{ item }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed()"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams()"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 修改属性对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed()"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams()"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 商品分类列表
      goodsCateList: [],
      // 级联选择器配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      // 级联选择器双向绑定的数组
      selectedCateKeys: [],
      // 被激活的页签的名称
      activeName: 'many',
      manyTableData: [], // 保存动态属性列表
      onlyTableData: [], // 保存静态参数列表
      addDialogVisible: false, // 添加属性对话框
      // 添加属性数据对象
      addForm: {
        arrr_name: '',
      },
      // 添加属性验证规则对象
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入属性名称',
            trigger: 'blur',
          },
        ],
      },
      // 修改属性对话框
      editDialogVisible: false,
      // 修改属性数据对象
      editForm: {
        attr_name: '',
      },
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入属性名称',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    // 商品分类列表
    async getGoodsCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$msg.error('查询商品分类列表失败')
      this.goodsCateList = res.data
    },
    handleChange() {
      this.getParamsData()
      // console.log(this.selectedCateKeys)
    },
    // 点击tab的处理函数
    handleClick() {
      // 判断是否选中三级分类
      if (!this.isBtnDisabled) {
        this.getParamsData()
      } else {
        this.$msg.info('请选择商品分类')
      }
    },
    // 获取参数列表
    async getParamsData() {
      // 发请求获取对应的数据
      const { data: res } = await this.$http.get(
        `categories/${Number(this.cateId)}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status !== 200)
        return this.$msg.error(`获取${this.activeName}失败`)

      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 给每个item加属性，不然文本框会有联动效果
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框的文本
        item.inputValue = ''
        // this.$set(item, 'inputValue', '')
        // this.$set(item, 'inputVisible', false)
      })
      // console.log(res.data)
      // 对响应数据进行处理
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else if (this.activeName === 'only') {
        this.onlyTableData = res.data
      }
    },
    // 关闭添加参数对话框事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) return this.$msg.error('添加参数失败')
        this.$msg.success('添加参数成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 修改参数对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('查询参数失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 关闭修改参数对话框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改参数
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) return this.$msg.error('更新参数失败')
        this.$msg.success('更新参数成功')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    // 通过id删除属性
    async removeParams(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该属性, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(attr_id)
      if (confirmResult === 'cancel') return this.$msg.info('已取消删除')
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('删除参数失败')
      this.$msg.success('删除参数成功')
      this.getParamsData()
    },
    // 文本框失去焦点或按下回车键触发函数
    handleInputConfirm(row) {
      // 如果内容不合法，空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }

      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = true
      this.saveAttrValues(row)
    },
    // 对attr_vals的操作保存到数据库
    async saveAttrValues(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('修改参数项失败')
      this.$msg.success('修改参数项成功')
    },
    // 点击按钮触发函数
    showInput(row) {
      row.inputVisible = true
      // 文本框自动获得焦点
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除参数可选项
    handleClosed(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrValues(row)
    },
  },
  computed: {
    // 判断按钮是否需要禁用
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 计算三级分类的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 计算对话框的title
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
  beforeMount() {
    this.getGoodsCateList()
  },
}
</script>

<style scoped>
.el-card {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 0 15px;
}
.input-new-tag {
  width: 150px;
}
</style>